package io;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

import constants.Constants;
import model.IState;

public class Save {
	
	private String file; 
	private IState s;
	
	public Save(IState s, String file){
		this.s = s;
		this.file = file;		
	} //Constructor 
	
	private String addExtensionIfMissing(String s){
		if(file.endsWith(Constants.IO.file_ext)){
			return s;
		}
		return s + Constants.IO.file_ext;
	}
	
	public void writeToFile(){
		file = addExtensionIfMissing(file);
		
		ObjectOutputStream outputStream = null;
		try{
			//Construct the LineNumberReader object
			outputStream = new ObjectOutputStream(new FileOutputStream(file,false));
			//Write the object
			outputStream.writeObject(s);

		} catch (FileNotFoundException ex){
			ex.printStackTrace();
		} catch (IOException ex){
			ex.printStackTrace();
		} finally {
			try{
				if(outputStream != null){
					outputStream.flush();
					outputStream.close();
				}
			} catch (IOException ex){
				ex.printStackTrace();
			}
		}
	}
}
